<script setup>
import { map, merge, pick } from 'lodash-es';
import dayjs from 'dayjs';
import { useRequest } from '@/hooks/requestHooks.js';
import { useWatch } from '@/hooks/useWatch.js';
import { barSeriesItem, lineSeriesItem } from '@/views/hooks.js';
import { basicLineXAxis, basicLineYAxis } from '@/components/chart/options/baseOptions.js';
import { getOrderData } from '@/api/index.js';
import CECharts from '@/components/chart/CECharts.vue';

const props = defineProps({
  month: { type: String | null, default: () => null },
  data: { type: Object | null, default: () => null },
  params: { type: Object | null, default: () => null },
});
const chartRef = ref(null);
const orderList = [
  { label: '报修设备编号', key: 'equCode' },
  { label: '报修设备名称', key: 'equName' },
  { label: '故障原因', key: 'reason' },
  { label: '工单状态', key: 'workOrderStatus' },
  { label: '处理人', key: 'handlePeople' },
  { label: '处理结果', key: 'handleResult' },
  { label: '处理时间', key: 'handleTime' },
  { label: '机构编号', key: 'institutionCode' },
  { label: '机构名称', key: 'buildingName' },
];
const headerStyle = { backgroundColor: '#d2e4e5', color: '#606266' };
const commOpts = {
  series: Array.from({ length: 3 }, (_, i) => {
    return i === 0 ? { ...barSeriesItem, yAxisIndex: 0 } : { ...lineSeriesItem, yAxisIndex: 1 };
  }),
  xAxis: merge({}, basicLineXAxis),
  yAxis: [
    merge({}, basicLineYAxis, {
      name: '单位：',
      nameTextStyle: { color: '#606266', fontSize: 12 },
    }),
    merge({}, basicLineYAxis, {
      name: '单位：%',
      nameTextStyle: { color: '#606266', fontSize: 12, align: 'right' },
    }),
  ],
  legend: {
    icon: 'rect',
    itemWidth: 10,
    itemHeight: 4,
    textStyle: { color: '#606266' },
    padding: [6, 25],
  },
  grid: { bottom: 0, top: 30, left: 0, right: 0, containLabel: true },
  dataZoom: null,
};
const lineExtraOpts = ref(
  merge({}, commOpts, {
    color: ['#4992ff', '#5afe5d', '#eda422'],
    dataset: {
      source: [],
      dimensions: [
        'date',
        { name: 'thisValue', displayName: '能耗量' },
        { name: 'togetherValue', displayName: '同比' },
        { name: 'chainValue', displayName: '环比' },
      ],
    },
  }),
);
const dsChartOpts = ref(
  merge({}, commOpts, {
    color: ['#4992ff', '#ee6666', '#eda422'],
    dataset: {
      source: [],
      dimensions: [],
    },
  }),
);
const pieExtraOpts = ref({
  title: {
    text: '系统能耗占比',
    left: '39.5%',
    top: '50%',
    textAlign: 'center',
    textVerticalAlign: 'middle',
    textStyle: { color: '#333', fontSize: 14 },
  },
  legend: {
    show: true,
    orient: 'vertical',
    x: '75%',
    y: 'center',
    textStyle: { color: '#333' },
  },
  tooltip: {
    trigger: 'item',
    formatter: params => `${params.name}: ${params.value.energyQuantity} (${params.percent}%)`,
  },
  dataset: {
    source: [],
    dimensions: ['equSysName', 'energyQuantity'],
  },
  series: [
    {
      type: 'pie',
      radius: ['60%', '80%'],
      center: ['40%', '50%'],
      label: {
        color: '#333',
        formatter: params => `${params.name}: ${params.value.energyQuantity} (${params.percent}%)`,
      },
      encode: {
        itemName: 'equSysName',
        value: 'energyQuantity',
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
    },
  ],
});
const [orderData, , runOrder] = useRequest(getOrderData, { manual: true });

useWatch(
  () => props.params,
  n => {
    const commParams = pick(n, ['buildingCodes', 'dateStart', 'projectType']);
    runOrder({ ...commParams });
  },
  { immediate: true, deep: true },
);

const getChartImgs = () => {
  const imgOpt = {
    type: 'jpeg',
    pixelRatio: 1,
    backgroundColor: '#fff',
  };
  return map(chartRef.value, v => v.$$chart.getDataURL(imgOpt).replace('data:image/jpeg;base64,', ''));
};
defineExpose({ getChartImgs });
</script>

<template>
  <div class="rep-wrapper rep-content" style="padding-bottom: 20px">
    <div class="rep-content-title">一、总览</div>
    <div class="rep-content-text">
      <span>{{ month ? dayjs(month).format('YYYY年M月') : '-年-月' }}</span>
      报告，监测（{{ data?.buildName ?? '-' }}）{{ data?.count ?? '--' }}家机构，总计能耗
      <span>{{ data?.sumEnergy ?? '--' }}</span>
      tce，总计碳排
      <span>{{ data?.sumDioxide ?? '--' }}</span>
      tco2。
    </div>
    <div class="rep-content-title">二、机构数据分析</div>
    <div v-for="(item, idx) in data?.listsInstitutionJCResults ?? []" :key="item.name + idx" class="rep-contList">
      <div class="rep-content-subtitle">2.{{ idx + 1 }} {{ item?.name ?? '--' }}机构数据分析</div>
      <div class="rep-content-subtitle">2.{{ idx + 1 }}.1 数据合计</div>
      <table class="rep-content-totalTable">
        <tr>
          <th>能耗类型</th>
          <th>能耗量(tce)</th>
          <th>环比(%)</th>
          <th>碳排量(tco2)</th>
          <th>环比(%)</th>
        </tr>
        <tr v-for="(itemEngType, index) in item?.typeEnergy ?? []" :key="index + itemEngType.energyType">
          <td>{{ itemEngType?.energyType ?? '--' }}</td>
          <td>{{ itemEngType?.quantity ?? '--' }}</td>
          <td>{{ itemEngType?.quantityChain ?? '--' }}</td>
          <td>{{ itemEngType?.carbon ?? '--' }}</td>
          <td>{{ itemEngType?.carbonChain ?? '--' }}</td>
        </tr>
      </table>
      <div class="rep-content-subtitle">2.{{ idx + 1 }}.2 机构分项能耗数据分析</div>
      <template v-for="(ECType, i) in item?.repEnergyList ?? []">
        <div class="rep-content-subtitle" :key="ECType?.energyName + i">
          2.{{ idx + 1 }}.2.{{ i + 1 }} 用{{ ECType?.energyName ?? '-' }}能耗数据分析
        </div>
        <CECharts
          ref="chartRef"
          type="line"
          class="chart-box"
          :options="
            merge({}, lineExtraOpts, {
              dataset: { source: ECType?.energyWarmList?.slice(0, -1) ?? [] },
              yAxis: [{ name: `单位：${ECType?.energyUnit ?? ''}` }],
            })
          "
        />
        <el-table :data="ECType?.energyWarmList ?? []" :header-cell-style="headerStyle">
          <el-table-column prop="date" label="统计时间" align="center" />
          <el-table-column prop="energyType" label="能耗类型" align="center" />
          <el-table-column prop="thisValue" label="能耗量" align="center" />
          <el-table-column prop="togetherValue" label="同比" align="center" />
          <el-table-column prop="chainValue" label="环比" align="center" />
        </el-table>
      </template>
      <div class="rep-content-subtitle">2.{{ idx + 1 }}.3 设备系统用电能耗数据分析</div>
      <CECharts
        ref="chartRef"
        type="pie"
        class="chart-box"
        :options="merge({}, pieExtraOpts, { dataset: { source: item?.listEquSysRate ?? [] } })"
      />
      <template v-for="(dsItem, dsIdx) in item?.listEquSysData?.columns ?? []">
        <div class="rep-content-subtitle" :key="dsItem.prop">
          2.{{ idx + 1 }}.3.{{ dsIdx + 1 }} {{ dsItem.label }}用电趋势
        </div>
        <CECharts
          ref="chartRef"
          type="line"
          class="chart-box"
          :options="
            merge({}, dsChartOpts, {
              dataset: {
                source: item?.listEquSysData?.dataSource ?? [],
                dimensions: ['date', ...(item?.listEquSysData?.dimensionsList?.[dsItem.prop] ?? [])],
              },
              yAxis: [{ name: `单位：${dsItem?.unit ?? ''}` }],
            })
          "
        />
      </template>
      <el-table :data="item?.listEquSysData?.dataSource ?? []" :header-cell-style="headerStyle">
        <el-table-column prop="date" label="统计时间" align="center" />
        <el-table-column
          v-for="dsColItem in item?.listEquSysData?.columns ?? []"
          :key="dsColItem.prop"
          :prop="dsColItem.prop"
          :label="dsColItem.label + '用电量(' + dsColItem.unit + ')'"
          align="center"
        />
      </el-table>
    </div>
    <div class="rep-content-title">三、告警统计</div>
    <div class="rep-content-subtitle">3.1 能耗告警统计</div>
    <el-table :data="data?.energyAlarm ?? []" :header-cell-style="headerStyle">
      <el-table-column prop="startTime" label="统计时间" width="100" align="center" />
      <el-table-column prop="energyTypeInfo" label="能耗类型" width="100" align="center" />
      <el-table-column prop="dataDate" label="超标时间" align="center" />
      <el-table-column prop="energyValue" label="实际能耗" align="center" />
      <el-table-column prop="checkType" label="超出考核类型" align="center" />
      <el-table-column prop="energyExceeding" label="超标量" align="center" />
      <el-table-column prop="enterpriseCode" label="机构编号" align="center" />
      <el-table-column prop="enterpriseName" label="机构名称" align="center" />
    </el-table>
    <div class="rep-content-subtitle">3.2 设备告警统计</div>
    <el-table :data="data?.facilityAlarm ?? []" :header-cell-style="headerStyle">
      <el-table-column prop="startTime" label="统计时间" width="100" align="center"></el-table-column>
      <el-table-column prop="equCode" label="设备编号" align="center"></el-table-column>
      <el-table-column prop="equName" label="设备名称" align="center"></el-table-column>
      <el-table-column prop="alarmReason" label="告警描述" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="enterpriseCode" label="机构编号" align="center"></el-table-column>
      <el-table-column prop="enterpriseName" label="机构名称" align="center"></el-table-column>
    </el-table>
    <div class="rep-content-title">四、设备维修工单统计</div>
    <div v-for="orderItem in orderData" :key="orderItem?.workOrderCode" class="u-mb20">
      <div class="u-df-spb u-fs14 u-mb5">
        <div class="u-fw-b" style="color: #303133">{{ orderItem?.workOrderCode }}</div>
        <div style="color: #909399">{{ orderItem?.startTime }}</div>
      </div>
      <el-descriptions title="" :column="3" size="small" border>
        <el-descriptions-item
          v-for="(item, index) in orderList"
          :key="index"
          :labelStyle="{
            color: '#606266',
            textAlign: 'left !important',
            backgroundColor: '#d2e4e5',
          }"
          :contentStyle="{
            color: '#606266',
            textAlign: 'left !important',
            backgroundColor: '#fff',
          }"
        >
          <template slot="label">
            <div class="u-df-st">
              <div class="info-descriptionsItem">{{ item.label }}</div>
            </div>
          </template>
          <div class="info-descriptionsItem">{{ orderItem?.[item.key] ?? '--' }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div v-show="orderData?.length <= 0" class="text-center u-fs14" style="color: #909399">暂无数据</div>
  </div>
</template>

<style lang="scss" scoped>
.chart-box {
  width: 100%;
  height: 200px;
  margin-bottom: 20px;
}
:deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
  background-color: #fff;
}
:deep(.el-table td) {
  background-color: #fff;
}
:deep(.el-table tr) {
  background-color: #fff;
}
:deep(.el-table__cell) {
  color: #606266 !important;
}
:deep(.el-table td.el-table__cell) {
  border-bottom: 1px solid #ebeef5 !important;
}
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #ebeef5 !important;
}
:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}
:deep(.el-descriptions .is-bordered .el-descriptions-item__cell) {
  border-color: #d4d4d4;
}
</style>
